package com.example.friend.service.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.example.RemoteJudgeService;
import com.example.common.core.constants.Constants;
import com.example.common.core.domain.Result;
import com.example.common.core.enums.ProgramType;
import com.example.common.core.enums.QuestionResult;
import com.example.common.core.enums.ResultCode;
import com.example.common.core.utils.ThreadLocalUtil;
import com.example.domain.dto.JudgeSubmitDTO;
import com.example.domain.vo.UserQuestionResultVO;
import com.example.friend.domain.question.Question;
import com.example.friend.domain.question.QuestionCase;
import com.example.friend.domain.question.es.QuestionES;
import com.example.friend.domain.user.dto.SubmitDTO;
import com.example.friend.elasticsearch.QuestionRepository;
import com.example.friend.mapper.question.QuestionMapper;
import com.example.security.exception.ServiceException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 23050
 * @version 1.0
 * @description: 判题服务类
 * @date 2025/5/2 11:40
 */
@Service
public class UserQuestionServiceImpl implements UserQuestionService{


    @Resource
    private QuestionRepository questionRepository;
    @Resource
    private QuestionMapper questionMapper;
    //api服务的service
    @Resource
    private RemoteJudgeService remoteJudgeService;

    //用户提交代码
    @Override
    public Result<UserQuestionResultVO> submit(SubmitDTO submitDTO) {
        Integer programType = submitDTO.getProgramType();
        //判断语言类型
        if (ProgramType.JAVA.getValue().equals(programType)){
            //处理JAVA语言的代码
            //根据questionid从es中查询题目的信息
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(submitDTO);
            //将judgeSubmitDTO传给判题服务，完成判题逻辑
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }


    //获取题目的信息
    private JudgeSubmitDTO assembleJudgeSubmitDTO(SubmitDTO submitDTO) {
        Long questionId = submitDTO.getQuestionId();
        //从es中查询数据
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        if (questionES!=null){
            BeanUtil.copyProperties(questionES,judgeSubmitDTO);
        }else{
            Question question = questionMapper.selectById(questionId);
            BeanUtil.copyProperties(question,judgeSubmitDTO);
            //将数据库中查询的数据存到es中
            questionES = new QuestionES();
            BeanUtil.copyProperties(question,questionES);
            questionRepository.save(questionES);
        }
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        judgeSubmitDTO.setExamId(submitDTO.getExamId());
        judgeSubmitDTO.setProgramType(submitDTO.getProgramType());
        //将用户写的代码和main函数拼接起来
        String userCode = codeConnect(submitDTO.getUserCode(),questionES.getMainFunc());
        judgeSubmitDTO.setUserCode(userCode);
        //题目测试用例list
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        //分成两个list
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setInputList(inputList);
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }

    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex!=-1){
            return userCode.substring(0,targetLastIndex) + "\n"+ mainFunc +"\n"+ userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }
}
